package cn.edu.cxcyzx.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.edu.cxcyzx.conf.Git;
import cn.edu.cxcyzx.entity.Gitee;
import cn.edu.cxcyzx.entity.GiteeVO;
import cn.edu.cxcyzx.entity.Project;
import cn.edu.cxcyzx.service.GiteeService;
import cn.edu.cxcyzx.supervisor.DaoFit;
import cn.edu.cxcyzx.supervisor.ResultDo;
import cn.edu.cxcyzx.util.HttpClientUtil;
import cn.edu.cxcyzx.util.Update_giteeAccessToken;

@Service("GiteeService")
public class GiteeServiceImpl implements GiteeService {
	
	@Resource
	public DaoFit daoFit;
	
	@Override
	public Gitee getGitee(String userId) {
		// TODO Auto-generated method stub
		
		return daoFit.getGiteeDao().getGitee(userId);
	}

	@Override
	public void insertGitee(Gitee gitee) {
		// TODO Auto-generated method stub
		if(gitee!=null){
			Gitee g=daoFit.getGiteeDao().getGitee(gitee.getUserId());
			if(g==null){
				daoFit.getGiteeDao().insertGitee(gitee);
			}
			
		}
		
	}

	@Override
	public void insertGitee_part(Gitee gitee) {
		// TODO Auto-generated method stub
		if(gitee!=null){
			daoFit.getGiteeDao().insertGitee_part(gitee);
		}
	}

	@Override
	public void update(Gitee gitee) {
		// TODO Auto-generated method stub
		if(gitee!=null){
			daoFit.getGiteeDao().updateGitee(gitee);
		}
	}

	@Override
	public void deleteGiteeBy_userId(String userId) {
		// TODO Auto-generated method stub
		daoFit.getGiteeDao().deleteGiteeBy_userId(userId);
	}

	@Override
	public void deleteGiteeBy_userName(String userName) {
		// TODO Auto-generated method stub
		daoFit.getGiteeDao().deleteGiteeBy_userName(userName);
	}

	@Override
	public Gitee getGiteeBy_code(String code) {
		// TODO Auto-generated method stub
		return daoFit.getGiteeDao().getGiteeBy_code(code);
	}

	@Override
	public Gitee updateCode(String code, String userId) {
		// TODO Auto-generated method stub
		Gitee gitee=new Gitee(userId, code);
		System.out.println("updateCode:"+gitee.toString());
		daoFit.getGiteeDao().updateGitee(gitee);
		return daoFit.getGiteeDao().getGitee(userId);
	}

	@Override
	public ResultDo<List<GiteeVO>> getAll() {
		// TODO Auto-generated method stub
		ResultDo<List<GiteeVO>> resultDo=new ResultDo<>();
		List<Gitee> list=daoFit.getGiteeDao().getAll();
		List<GiteeVO> result=new ArrayList<GiteeVO>();
		if(list==null||list.size()<=0){
			resultDo.setSuccess(false);
			resultDo.setMessage("0条记录");
		}else{
			Iterator<Gitee> iterator=list.iterator();
			// List<Gitee> ---->  List<GiteeVO>  
			while (iterator.hasNext()) {
				Gitee gitee =Update_giteeAccessToken.update((Gitee) iterator.next(),daoFit.getGiteeDao());
				List<NameValuePair> params=new ArrayList<>();
				params.add(new BasicNameValuePair("access_token",gitee.getAccess_token()));
				JSONObject res=JSONObject.parseObject(HttpClientUtil.doGet(Git.gitee_userInfo_url,params));
				String name=res.getString("name");
				String html_url=res.getString("html_url");
				result.add(new GiteeVO(gitee,name,html_url));
			}
			resultDo.setSuccess(true);
			resultDo.setResult(result);
		}
		return resultDo;
	}

	@Override
	public ResultDo<String> have_proName(String proName, String userId) {
		// TODO Auto-generated method stub
		ResultDo<String> resultDo=new ResultDo<>();
		Gitee g=daoFit.getGiteeDao().getGitee(userId);
		if(g==null){
			resultDo.setSuccess(false);
			resultDo.setMessage("gitee未授权，请先授权gitee");
		}else{
			//判断token是否过期
			g=Update_giteeAccessToken.update(g, daoFit.getGiteeDao());
			List<NameValuePair> params=new ArrayList<>();
			params.add(new BasicNameValuePair("access_token",g.getAccess_token()));
			params.add(new BasicNameValuePair("sort","full_name"));
			params.add(new BasicNameValuePair("page","1"));
			params.add(new BasicNameValuePair("per_page","20"));
			//获取数据
			String res=HttpClientUtil.doGet(Git.gitee_userAllPro_url, params);
			JSONArray jsonArray=JSONArray.parseArray(res);
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jo=jsonArray.getJSONObject(i);
				String name=jo.getString("name");
				if(proName.trim().equals(name)){
					resultDo.setSuccess(true);
					resultDo.setResult(jo.getString("full_name"));
					return resultDo;
				}
				
			}
			resultDo.setSuccess(false);
			resultDo.setMessage("未在Gitee上创建此项目，请先到Gitee上创建项目.");
		}
		return resultDo;
	}

	@Override
	public ResultDo<JSONObject> gitee_userInfo(String userId) {
		// TODO Auto-generated method stub
		ResultDo<JSONObject> resultDo=new ResultDo<>();
		Gitee g=daoFit.getGiteeDao().getGitee(userId);
		if(g==null){
			resultDo.setSuccess(false);
			resultDo.setMessage("该用户未进行Gitee授权");
		}else{
			g=Update_giteeAccessToken.update(g, daoFit.getGiteeDao());
			System.out.println("userId:"+userId+",gitee:"+g.toString());
			List<NameValuePair> params=new ArrayList<>();
			params.add(new BasicNameValuePair("access_token",g.getAccess_token()));
			String res=HttpClientUtil.doGet(Git.gitee_userInfo_url, params);
			if(res==null||"".equals(res.trim())){
				resultDo.setSuccess(false);
				resultDo.setMessage("获取失败");
			}else{
				JSONObject jo=JSONObject.parseObject(res);
				resultDo.setSuccess(true);
				resultDo.setResult(jo);
			}
			
		}
		return resultDo;
	}

	@Override
	public ResultDo<String> isInGiteePro(String userId, int projectId) {
		// TODO Auto-generated method stub
		ResultDo<String> resultDo=new ResultDo<>();
		ResultDo<JSONObject> resultDo2=this.gitee_userInfo(userId);
		if(!resultDo2.isSuccess()){
			//用户未授权
			resultDo.setSuccess(false);
			resultDo.setMessage(resultDo2.getMessage());
		}else{
			String uesr_id=resultDo2.getResult().getString("id");
			System.out.println("uesr_id:"+uesr_id);
			Project pro=daoFit.getProjectDao().getProjectBy_projectId(projectId);
			System.out.println("pro:"+pro.toString());
			ResultDo<JSONObject> resultDo3=this.gitee_userInfo(pro.getLeaderId());
			if(!resultDo3.isSuccess()){
				//项目的创建作者未授权gitee
				resultDo.setSuccess(false);
				resultDo.setMessage("您未授权Gitee,请尽快授权");
			}else{
				Gitee g=daoFit.getGiteeDao().getGitee(pro.getLeaderId());
				g=Update_giteeAccessToken.update(g, daoFit.getGiteeDao());
				List<NameValuePair> params=new ArrayList<>();
				params.add(new BasicNameValuePair("access_token",g.getAccess_token()));
				//获取数据
				String url=Git.gitee_proAllMembers+pro.getGitee_pro_full_name()+"/collaborators";
				System.out.println("url:"+url);
				System.out.println("token:"+g.getAccess_token());
				String res=HttpClientUtil.doGet(url, params);
				if(res==null){
					resultDo.setMessage("获取失败！！！");
					resultDo.setSuccess(false);
					return resultDo;
				}
				JSONArray jsonArray=JSONArray.parseArray(res);
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jo=jsonArray.getJSONObject(i);
					String id=jo.getString("id");
					System.out.println("id:"+id);
					if(uesr_id.trim().equals(id)){
						//根据id判断用户是否存在
						resultDo.setSuccess(true);
						return resultDo;
					}
					
				}
				resultDo.setMessage("该用户未在gitee上参加此项目");
				resultDo.setSuccess(false);
			}
		}
		return resultDo;
	}

	@Override
	public ResultDo<String> isHaveBranch(int projectId, String branch) {
		// TODO Auto-generated method stub
		ResultDo<String> resultDo=new ResultDo<>();
		Project pro=daoFit.getProjectDao().getProjectBy_projectId(projectId);
		Gitee g=daoFit.getGiteeDao().getGitee(pro.getLeaderId());
		g=Update_giteeAccessToken.update(g, daoFit.getGiteeDao());
		
		List<NameValuePair> params=new ArrayList<>();
		params.add(new BasicNameValuePair("access_token",g.getAccess_token()));
		
		String url=Git.getOneBranch+pro.getGitee_pro_full_name()+"/branches/"+branch;
		String res=HttpClientUtil.doGet(url, params);
		if(res==null){
			resultDo.setMessage("404 Branch does not exist Not Found!");
			resultDo.setSuccess(false);
			return resultDo;
		}
		resultDo.setSuccess(true);
		return resultDo;
	}

}
